import { ref } from 'vue'
import { ElLoading, ElMessage } from 'element-plus'
import HttpUtil from '@/util/http.util'

export function useCalculator() {
  const subjects = ref([])
  const history = ref([])
  const result = ref(null)
  const loading = ref(false)

  // 加载科目数据
  const loadSubjects = async () => {
    try {
      const data = await HttpUtil.get('/reward/subjects')
      subjects.value = data
    } catch (error) {
      handleRequestError(error)
    }
  }

  // 加载历史计算记录
  const loadDataHistory = async () => {
    try {
      const data = await HttpUtil.get('/reward/result')
      history.value = data
      if (data.length > 0) {
        result.value = data[0]
      }
    } catch (error) {
      handleRequestError(error)
    }
  }

  // 计算奖励
  const calculate = async (formData) => {
    loading.value = true
    const loadingInstance = ElLoading.service({ fullscreen: true })

    try {
      result.value = await HttpUtil.post('/reward/calculate', formData)
      await loadDataHistory()
    } catch (error) {
      handleRequestError(error)
    } finally {
      loading.value = false
      loadingInstance.close()
    }
  }

  // 删除历史记录
  const removeHistory = async (id) => {
    try {
      const res = await HttpUtil.deleteById("/reward", id)
      ElMessage({
        type: res.code === 200 ? 'success' : "warning",
        message: res.msg,
        duration: 2000,
        showClose: true
      })
      await loadDataHistory()
    } catch (error) {
      handleRequestError(error)
    }
  }

  // 批量删除历史记录
  const batchRemoveHistory = async (selectedRecords) => {
    try {
      const selectedIds = selectedRecords.map(r => r.id)
      const res = await HttpUtil.deleteBatch("/reward", selectedIds)
      
      ElMessage({
        type: res.code === 200 ? 'success' : "warning",
        message: res.msg,
        duration: 2000,
        showClose: true
      })
      await loadDataHistory()
    } catch (error) {
      handleRequestError(error)
    }
  }

  // 下载PDF报告
  const downloadPdf = async (id) => {
    try {
      const blob = await HttpUtil.download(`/reward/download/${id}`)
      const link = document.createElement('a')
      link.href = URL.createObjectURL(blob)
      link.download = 'reward-report.pdf'
      link.click()
      URL.revokeObjectURL(link.href)

      ElMessage.success('PDF 下载成功')
    } catch (error) {
      console.error(error)
      ElMessage.error('下载失败')
    }
  }

  // 错误处理
  const handleRequestError = (error) => {
    const errorMessages = {
      network: '网络连接异常，请检查网络',
      default: '操作失败，请稍后重试'
    }

    let message = errorMessages.default
    if (error.status) {
      message = `请求失败 (${error.status}): ${error.data?.message || '服务器错误'}`
    } else if (error.isNetworkError) {
      message = errorMessages.network
    }

    console.error('请求错误:', error)
    ElMessage({
      type: 'error',
      message,
      duration: 5000,
      showClose: true
    })
  }

  return {
    subjects,
    history,
    result,
    loading,
    loadSubjects,
    loadDataHistory,
    calculate,
    removeHistory,
    batchRemoveHistory,
    downloadPdf,
    handleRequestError
  }
} 